package solvers;

import model.Graph;
import model.Itinerary;
import model.Population;

public final class CockroachSolver extends Solver {

    private Population population;
    private int numberOfIterations;
    private int[] bestSolutionTab;
    private int sumInBestSolution;
    private int visual;


    public CockroachSolver(Graph graph, Population population, int numberOfIterations, int visual) {
        super(graph);
        this.population = population;
        this.numberOfIterations = numberOfIterations > 1 ? numberOfIterations : 1;
        this.visual = visual;
        this.bestSolutionTab = new int[graph.getSize()];
        this.sumInBestSolution = Integer.MAX_VALUE;
    }

    public Population getPopulation() {
        return population;
    }

    public int getNumberOfIterations() {
        return numberOfIterations;
    }

    @Override
    public Itinerary solve() {
        for (int i = 0; i < numberOfIterations; i++) {
            swarm();
            disperse();
            beRuthless();
        }
        return new Itinerary(bestSolutionTab, graph);
    }


    private void swarm() {
        //System.out.println(population.getPopulation().size());
        for (Itinerary itin1 : population.getPopulation()) {
            for (Itinerary itin2 : population.getPopulation()) {
                //System.out.println("itin sum " + itin2.getSum());
                if(itin1.getSum() < itin2.getSum() && itin1.similarity(itin2) > visual) {
                      itin2.move(itin1);
                      if(itin2.getSum() < sumInBestSolution) {
                          bestSolutionTab = itin2.getTab().clone();
                       }
                }
            }
        }
    }
    
    private void disperse() {
        for (Itinerary itin : population.getPopulation()) {
            itin.randomMove();
        }
    }

    private void beRuthless() {
        population.getRandomItineraryFromPopulation().set(bestSolutionTab.clone());
    }
}
